/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.core.commands.diagram;

import org.eclipse.gef.commands.Command;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.NamedElement;

import com.cea.papyrus.core.editor.ModelManager;
import com.cea.papyrus.diagraminterchange2.di2.Diagram;
import com.cea.papyrus.diagraminterchange2.di2.GraphElement;
import com.cea.papyrus.diagraminterchange2.di2.SemanticModelBridge;
import com.cea.papyrus.diagraminterchange2.di2.Uml1SemanticModelBridge;


/**
 * A command to remove a shape from its parent.
 * The command can be undone or redone.
 */
public class DiagramDeleteCommand extends Command {

	

	/**
	 * ShapeDiagram to remove from.
	 */
	private final GraphElement diagram;
	
	/**
	 * 
	 */
	private ModelManager modelManager;

	/**
	 * True, if child was removed from its parent.
	 */
	private boolean wasRemoved;
	/**
	 * the owner of the diagram
	 */
	private SemanticModelBridge owner=null;

	/**
	 * Create a command that will remove the shape from its parent.
	 * 
	 * @param child    the Shape to remove
	 * @param modelManager 
	 * @param diagram 
	 * @param parent the ShapesDiagram containing the child
	 * 
	 * @throws IllegalArgumentException if any parameter is null
	 */
	public DiagramDeleteCommand(GraphElement diagram, ModelManager modelManager) {
		if (diagram == null) {
			throw new IllegalArgumentException();
		}
		this.modelManager=modelManager;
		setLabel("Diagram deletion");
		this.diagram = diagram;
		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean canUndo() {
		return wasRemoved;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void execute() {
		owner= ((Diagram)this.diagram).getOwner();
	 wasRemoved=modelManager.removeDiagram((Diagram)this.diagram);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void redo() {
		// executte the command again
		execute();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	@SuppressWarnings("unchecked")
	public void undo() {
		// add the child and reconnect its connections
		((Diagram)this.diagram).setOwner(this.owner);
		modelManager.addDiagram((Diagram) this.diagram);
		//in order to force the uml listener of the tree diagram to trigger and refresh the outline.
		Element elt=((Uml1SemanticModelBridge) this.owner).getElement();
		if(elt instanceof NamedElement){
		((NamedElement)elt).setName(((NamedElement)elt).getName());
		}
	}
}
